$(document).ready(function() {
    $('#loginform-username').val("");
    $('#loginform-password').val("");
    $('#loginform-mobile').val("");
    $('#loginform-smscode').val("");
    $("#switch_login").click(function () {
        $("#login_account").toggle();
        $("#login_sms_code").toggle();
        var login_sms_code_hidden = $("#login_sms_code").is(":hidden");
        if (login_sms_code_hidden === true) {
            $('#switch_login').html("手机动态码登录");
            $('#loginform-mobile').val("");
            $('#loginform-smscode').val("");
        }
        else {
            $('#switch_login').html("账号密码登录");
            $('#loginform-username').val("");
            $('#loginform-password').val("");
        }
    });

    //fix mn-height
    $(".content-wrapper, .right-side").css("min-height",'600px');

});


//发送验证码时添加cookie
function addCookie(name,value,expiresHours){
    var cookieString=name+"="+escape(value);
    //判断是否设置过期时间,0代表关闭浏览器时失效
    if(expiresHours>0){
        var date=new Date();
        date.setTime(date.getTime()+expiresHours*1000);
        cookieString=cookieString+";expires=" + date.toUTCString();
    }
    document.cookie=cookieString;
}
//修改cookie的值
function editCookie(name,value,expiresHours){
    var cookieString=name+"="+escape(value);
    if(expiresHours>0){
        var date=new Date();
        date.setTime(date.getTime()+expiresHours*1000); //单位是毫秒
        cookieString=cookieString+";expires=" + date.toGMTString();
    }
    document.cookie=cookieString;
}
//根据名字获取cookie的值
function getCookieValue(name){
    var strCookie=document.cookie;
    var arrCookie=strCookie.split("; ");
    for(var i=0;i<arrCookie.length;i++){
        var arr=arrCookie[i].split("=");
        if(arr[0]==name){
            return unescape(arr[1]);
            break;
        }
    }

}

$(function(){
    $("#second").click(function (){
        sendCode($("#second"));
    });
    v = getCookieValue("secondsremained_login") ? getCookieValue("secondsremained_login") : 0;//获取cookie值
    if(v>0){
        settime($("#second"));//开始倒计时
    }
})
//发送验证码
function sendCode(obj){
    var site = 'http://yun.ucrm.com.cn/';
    var mobile = $("#loginform-mobile").val();
    //检查手机是否合法
    var result = isPhoneNum();
    if(result){
        //检查手机号码是否存在
        var exists_result = "";
        exists_result = dbCheckMobileExists(site+'site/check-mobile-exists',{"mobile":mobile});
        if(exists_result){
            doPostBack(site+'sms/send-login-code',{"mobile":mobile});
            addCookie("secondsremained_login",60,60);//添加cookie记录,有效时间60s
            settime(obj);//开始倒计时
        }
    }
}

//检查手机号码是否存在
function dbCheckMobileExists(url,queryParam){
    var data = "";
    $.ajax({
        async : false,
        cache : false,
        type : 'POST',
        url : url,// 请求的action路径
        data:queryParam,
        error : function() {// 请求失败处理函数
        },
        success:function(data){
            if(data === 'Success'){
                result =  true;
            }
            else{
                alert('该手机号码不存在！');
                result =  false;
            }
        },
        failure: function () {
            result =  false;
        }
    });
    return result;
}
//将手机利用ajax提交到后台的发短信接口
function doPostBack(url,queryParam) {
    $.ajax({
        async : false,
        cache : false,
        type : 'POST',
        url : url,// 请求的action路径
        data:queryParam,
        error : function() {// 请求失败处理函数
        },
        success:function(result){
            if(result=='Success'){
                alert('短信发送成功，验证码10分钟内有效,请注意查看手机短信。如果未收到短信，请在60秒后重试！');
            }
            else{
                alert('短信发送失败，请和网站客服联系！');
                return false;
            }
        }
    });
}

//开始倒计时
var countdown;
function settime(obj) {
    countdown=getCookieValue("secondsremained_login") ? getCookieValue("secondsremained_login") : 0;
    if (countdown ==0) {
        obj.removeAttr("disabled");
        obj.val("获取验证码");
        return;
    } else {
        obj.attr("disabled", true);
        obj.val(countdown + "秒后重发");
        countdown--;
        editCookie("secondsremained_login",countdown,countdown+1);
    }
    setTimeout(function() { settime(obj) },1000) //每1000毫秒执行一次
}
//校验手机号是否合法
function isPhoneNum(){
    var phonenum = $("#loginform-mobile").val();
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if(!myreg.test(phonenum)){
        alert('请输入有效的手机号码！');
        $("#loginform-mobile").focus();
        return false;
    }else{
        return true;
    }
}



function Investment_calculation(){
	invest_date = $('#crmcustomer-invest_date').val();
	start_pays_date = $('#crmcustomer-start_pays_date').val();
	invest_amount = $('#crmcustomer-invest_amount').val();
	invest_deadline = $('#crmcustomer-invest_deadline').val();
	interest_rate = $('#crmcustomer-interest_rate').val()/100;
	
	//月收益计算
	month_earnings = Number(invest_amount*interest_rate/12).toFixed(2);
	//末期利息计算
    /*
	begin_time = new Date(invest_date);
	end_time = new Date(start_pays_date);
	var dif = end_time.getTime() - begin_time.getTime();
	var day = Math.floor(dif / (1000 * 60 * 60 * 24));
	last_earnings = Number(day*month_earnings/30).toFixed(2);
	*/
    last_earnings = Number(invest_amount*1+month_earnings*1).toFixed(2);
	//总收益计算
    /*
	total_earnings = Number(month_earnings*(invest_deadline-1)*1+last_earnings*1).toFixed(2);
	*/
    total_earnings  = Number(month_earnings*invest_deadline).toFixed(2);
	
	$("#crmcustomer-month_earnings").attr("value",month_earnings);
	$("#crmcustomer-last_earnings").attr("value",last_earnings);
	$("#crmcustomer-total_earnings").attr("value",total_earnings);
}

function Expiration_date_calculation(){
    invest_date = $('#crmcustomer-invest_date').val();
    invest_deadline = $('#crmcustomer-invest_deadline').val();
    if(invest_date && invest_deadline){
        var splitstr= new Array();
        splitstr=invest_date.split('-');
        year = splitstr[0]*1;
        month = splitstr[1]*1;
        day = splitstr[2]*1;
        last_month = month+invest_deadline*1;
        if(last_month > 12){
            year = year+1;
            month = last_month-12;
        }else{
            month = last_month;
        }

        if(day==1){

            if(month==1){
                year  = year-1;
                month=12;
            }
            else{
                month = month-1;
            }
            if(month ==1 || month ==3 || month ==5 || month ==7 || month ==8 || month ==10 || month ==12    ){
                day = 31;
            }
            else if(month==2){
                day = 28;
            }
            else{
                day = 30;
            }
        }
        else{
            day = day-1;
        }

        if(month<10){
            month = '0'+month;
        }
        if(day<10){
            day = '0'+day;
        }
        expiration_date = year+'-'+month+'-'+day;
        //alert(expiration_date);
        $("#crmcustomer-expiration_date").attr("value",expiration_date);

    }
}

//CRM-Customer
$('#crmcustomer-invest_amount').change(function(){
	Investment_calculation();
});
$('#crmcustomer-invest_deadline').change(function(){
	Investment_calculation();
    Expiration_date_calculation();
});
$('#crmcustomer-interest_rate').change(function(){
	Investment_calculation();
});

$('#crmcustomer-invest_date').change(function(){
	invest_date = $('#crmcustomer-invest_date').val();
	if(invest_date){
		var splitstr= new Array();
		splitstr=invest_date.split('-');
		year = splitstr[0]*1;
		month = splitstr[1]*1;
		day = splitstr[2]*1;
		if(month==12){
			year = year+1;
			month = 1;
		}else{
			month = month+1;
		}
		
		if(day==1){
            if(month==1){
                year = year-1;
                month = 12;
            }
            else{
                month = month - 1;
            }

            if(month ==1 || month ==3 || month ==5 || month ==7 || month ==8 || month ==10 || month ==12    ){
                day = 31;
            }
            else if(month==2){
                day = 28;
            }
            else{
                day = 30;
            }
		}
		else{
           day = day - 1;
		}

        if(month<10){
            month = '0'+month;
        }
        if(day<10){
            day = '0'+day;
        }

		start_pays_date = year+'-'+month+'-'+day;

		$("#crmcustomer-start_pays_date").attr("value",start_pays_date);
        $("#crmcustomer-next_pay_date").attr("value",start_pays_date);
		Investment_calculation();

	}
    Expiration_date_calculation();
});


$(document).ready(function(){
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var month2 =  now.getMonth() -2;
    var today = year+'-'+month+'-'+day;
    var last_year = year+'-'+month2+'-'+day;
    $('#crmreport-start_date').attr('value',last_year);
    $('#crmreport-end_date').attr('value',today);
});

//选择用户layer弹窗
$('#select-user').on('click', function(){
    object_id = $("#object_id").val();
    layer.open({
        type: 2,
        title: '选择用户',
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area : ['800px' , '600px'],
        content: '/sys/layer/user?object_id='+object_id
    });
});

function selected_user(object_id,user_id,username){
    //alert(object_id);
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.$('#'+object_id).empty();
    parent.$('#'+object_id).prepend("<option value="+user_id+">"+username+"</option>");
    parent.layer.tips('选择完成', '#'+object_id, {time: 3000});
    parent.layer.close(index);
}

function selected_item(object_id,item_id,item_name){
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.$('#'+object_id).empty();
    parent.$('#'+object_id).prepend("<option value="+item_id+">"+item_name+"</option>");
    parent.layer.tips('选择完成', '#'+object_id, {time: 3000});
    parent.layer.close(index);
}

//选择商品layer弹窗
$('#select-goods').on('click', function(){
    object_id = $("#object_id").val();
    layer.open({
        type: 2,
        title: '选择商品',
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area : ['800px' , '600px'],
        content: '/crm/layer/goods?object_id='+object_id
    });
});

//选择客户layer弹窗
$('#select-customer').on('click', function(){
    object_id = $("#object_id").val();
    layer.open({
        type: 2,
        title: '选择客户',
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area : ['600px' , '480px'],
        content: '/customer/layer?object_id='+object_id
    });
});

function selected_customer(object_id,customer_id,name,get_person){
    //alert(object_id);
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.$('#'+object_id).empty();
    parent.$('#'+object_id).prepend("<option value="+customer_id+">"+name+"</option>");

    if(get_person===1){
        $.ajax({
            async : false,
            cache : false,
            type : 'POST',
            url : "/customer-person/lists?customer_id="+customer_id,// 请求的action路径
            data:'',
            error : function() {// 请求失败处理函数
                alert('请求处理失败，请重试。');
            },
            success:function(data){
                parent.$("#saleschance-customer_person_id").html(data);
            }
        });
    }
    parent.layer.tips('选择完成', '#'+object_id, {time: 3000});
    parent.layer.close(index);

}

function ajax_list_customer_person(customer_id,object_id){
        $.ajax({
            async : false,
            cache : false,
            type : 'POST',
            url : "/crm/ajax/customer-person-list?customer_id="+customer_id,// 请求的action路径
            data:'',
            error : function() {// 请求失败处理函数
                alert('请求处理失败，请重试。');
            },
            success:function(result){
                $("#"+object_id).html(result);
            }
        });


}


//自动生成商品编码
$("#generate-code").click(function(){
    $.ajax({
        async : false,
        cache : false,
        type : 'POST',
        url : '/goods/get-code',// 请求的action路径
        data:'',
        error : function() {// 请求失败处理函数
            alert('请求处理失败，请重试。');
        },
        success:function(data){
            var json_obj = jQuery.parseJSON(data);
            if(json_obj.result==1){
                $("#goods-code").val(json_obj.code);
                $("#goods-code").attr('readonly',true);
                $("#generate-code").addClass('disabled');
            }
            else{
                alert('商品编码生成失败');
                return false;
            }
        }
    });
});

//打印区域选择函数
function preview()
{
    bdhtml=window.document.body.innerHTML;
    sprnstr="<!--startprint-->";
    eprnstr="<!--endprint-->";
    prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
    prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML=prnhtml;
    window.print();
    window.history.go(0);
}

//弹窗选择用户，双向选择列表
function multi_select_user()  {
    winopen("/user/dialog", 730, 600);
}

/*打开弹出窗口*/
function winopen(url, w, h) {
    url = fix_url(url);
    $("html,body").css("overflow","hidden");
    $("div.shade").show();
    var _body = $("body").eq(0);
    if ($("#dialog").length == 0){

        if (!is_mobile()) {
            _body.append("<div id=\"dialog\" ><iframe class=\"myFrame\" src='" + url + "' style='width:" + w + "px;height:100%' scrolling='auto' ></iframe></div>");
            $("#dialog").css({
                "width" : w,
                "height" : h,
                "position" : "fixed",
                "z-index" : "2000",
                "top" : ($(window).height() / 2 - h / 2),
                "left" : (_body.width() / 2 - w / 2),
                "background-color" : "#ffffff"
            });
        } else {
            $("div.shade").css("width", _body.width());
            _body.append("<div id=\"dialog\" ><iframe class=\"myFrame\" src='" + url + "' style='width:100%;height:100%' scrolling='auto' ></iframe></div>");
            $("#dialog").css({
                "width" : _body.width(),
                "height" : h,
                "position" : "fixed",
                "z-index" : "2000",
                "top":0,
                "left":0,
                "background-color" : "#ffffff"
            });
        }
    } else {
        $("#dialog").show();
    }
}

var toScrollFrame = function(iFrame, mask) {
    if (!navigator.userAgent.match(/iPad|iPhone/i))
        return false;
    //do nothing if not iOS devie

    var mouseY = 0;
    var mouseX = 0;
    jQuery(iFrame).ready(function() {
        jQuery(iFrame).contents()[0].body.addEventListener('touchstart', function(e) {
            mouseY = e.targetTouches[0].pageY;
            mouseX = e.targetTouches[0].pageX;
        });

        jQuery(iFrame).contents()[0].body.addEventListener('touchmove', function(e) {
            e.preventDefault();

            var box = jQuery(mask);
            box.scrollLeft(box.scrollLeft() + mouseX - e.targetTouches[0].pageX);
            box.scrollTop(box.scrollTop() + mouseY - e.targetTouches[0].pageY);
        });
    });

    return true;
};

/* 判断是否是移动设备 */
function is_mobile() {
    return navigator.userAgent.match(/mobile/i);
}

/*联系人显示格式转换*/
function fix_url(url) {
    var ss = url.split('?');
    url = ss[0] + "?";
    for (var i = 1; i < ss.length; i++) {
        url += ss[i] + "&";
    }
    if (ss.length > 0) {
        url = url.substring(0, url.length - 1);
    }
    return url;
}

/* 关闭弹出窗口*/
function winclose() {
    dialog_close();
}

function dialog_close() {
    parent.$("html,body").css("overflow", "auto");
    parent.$("div.shade").hide();
    parent.$("#dialog").css({
        "z-index" : -1
    });
    parent.$("#dialog").remove();

}



/*赋值*/
function set_val(name, val) {
    if ($("#" + name + " option").length > 0) {
        $("#" + name + " option[value='" + val + "']").attr("selected", "selected");
        return;
    }

    if (($("#" + name).attr("type")) === "checkbox") {
        if (val == 1) {
            $("#" + name).attr("checked", true);
            return;
        }
    }
    if ($("." + name).length > 0) {
        if (($("." + name).first().attr("type")) === "checkbox") {
            var arr_val = val.split(",")
            for (var s in arr_val) {
                $("input." + name + "[value=" + arr_val[s] + "]").attr("checked", true);
            }
        }
    }

    if ($(":radio[name='" + name+"'][value='"+val+"']").length>0){
        $(":radio[name=" + name+"][value="+val+"]").attr("checked",true);
    }

    if (($("#" + name).attr("type")) === "text") {
        $("#" + name).val(val);
        return;
    }
    if (($("#" + name).attr("type")) === "hidden") {
        $("#" + name).val(val);
        return;
    }
    if (($("#" + name).attr("rows")) > 0) {
        $("#" + name).text(val);
        return;
    }
}

/*联系人显示格式转换*/
function contact_conv(val) {
    var arr_temp = val.split(";");
    var html = "";
    for (key in arr_temp) {
        if (arr_temp[key] != '') {
            data = arr_temp[key].split("|")[1];
            id = arr_temp[key].split("|")[1];
            name = arr_temp[key].split("|")[0];
            title = arr_temp[key].split("|")[0];
            html += conv_inputbox_item(id, name, title, data)
            //html +=  '<span data="' + arr_temp[key].split("|")[1] + '" onmousedown="return false"><nobr>' + arr_temp[key].split("|")[0] + '<a class=\"del\" title=\"删除\"><i class=\"fa fa-times\"></i></a></nobr></span>';
        }
    }
    return html;
}

/*联系人显示格式转换*/
function conv_address_item(id, name) {
    html = '<nobr><label>';
    html += '		<input class="ace" type="checkbox" name="addr_id" value="' + id + '"/>';
    html += '		<span class="lbl">' + name + '</span></label></nobr>';
    return html;
}

function conv_inputbox_item(id, name, title, data) {
    if (data !== undefined) {
        html = "<span data=\"" + data + "\" id=\"" + id + "\">";
    } else {
        html = "<span id=\"" + id + "\">";
    }
    html += "<nobr><b  title=\"" + title + "\">" + name + "</b>";
    html += "<a class=\"del\" title=\"删除\"><i class=\"fa fa-times\"></i></a></nobr></span>";
    return html;
}


$(document).on("click", ".inputbox .address_list a.del", function() {
    $(this).parent().parent().remove();
});

function save() {
    $("#rc select option").each(function(i) {
        //alert($(this));
        //email = ($(this).html().split(";")[1].split("&")[0]);
        id = $(this).val();
        name = jQuery.trim($(this).text()).replace(/<.*>/, '');
        //alert(id);
        html = conv_inputbox_item(id, name, name, id);
        //$("#admin-user-list", parent.document).append(html);
        //alert(html);
        parent.$("#admin_list .address_list").append(html);
        //alert('ooo');
    });
    winclose();
}

function create() {
    $("#opmode").val("add");
    $("#id").val("");
    $("#admin-user").val("");
    $("#admin_list span.address_list span").each(function(){
        $("#admin-user").val($("#admin-user").val() + $(this).text().replace(';', '') + '|' + $(this).attr("data") + ";");
    });
    sendForm("main-form", "/schedule/create","/schedule/index");

};

function sendForm(formId, post_url,return_url) {
    if ($("#ajax").val() == 1) {
        var vars = $("#" + formId).serialize();
        $.ajax({
            type : "POST",
            url : post_url,
            data : vars,
            dataType : "json",
            success : function(data) {
                if (data.status) {
                    ui_alert(data.info, function() {
                        if (return_url) {
                            location.href = return_url;
                        }else{
                            return data.status;
                        }
                    });
                } else {
                    ui_error(data.info);
                }
            }
        });
    } else {
        $("#" + formId).attr("action", post_url);
        $("#" + formId).submit();
    }
}
